using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics.Contracts;
using Konst3d.Efficiency.Suite;

namespace Konst3d.Efficiency.Suite.SparsedBinary
{
    internal class MonitorCollectionStorage : IMonitorCollection, IDisposable
    {
        #region Types

        public delegate void ItemAddedOrRemoved(MonitorCollectionStorage sender, int id);

        #endregion // Types

        #region Constants

        private const string MONITOR_FILE_SEARCH_PATTERN = "*.monitor";

        #endregion // Constants

        #region Events

        public event ItemAddedOrRemoved MonitorAdded;
        public event ItemAddedOrRemoved MonitorRemoved;

        #endregion // Events

        #region Properties

        public string Folder
        {
            get;
            private set;
        }

        public IMonitor this[int id]
        {
            get
            {
                Contract.Assert(id > 0);

                return _monitors[id];
            }
        }

        #endregion // Properties

        #region Create/Open/Delete Methods

        public static MonitorCollectionStorage Create(string folder, ICryptographicEngine cryptographicEngine)
        {
            Contract.Requires(!String.IsNullOrEmpty(folder));
            Contract.Requires(cryptographicEngine != null);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            return new MonitorCollectionStorage(folder, cryptographicEngine);
        }

        public static MonitorCollectionStorage Open(string folder, ICryptographicEngine cryptographicEngine)
        {
            Contract.Requires(!String.IsNullOrEmpty(folder));
            Contract.Requires(cryptographicEngine != null);

            if (!Directory.Exists(folder))
            {
                throw new IOException(String.Format("Directory '{0}' doesn't exists.", folder));
            }

            // in the future, loading should be done here - also with progress notifications and logging...

            return new MonitorCollectionStorage(folder, cryptographicEngine);
        }

        public void Delete()
        {
            Contract.Assert(!_disposed);

            foreach (var monitor in _monitors.Values)
            {
                monitor.Delete();
            }

            Directory.Delete(Folder, true);

            Dispose();
        }

        #endregion // Create/Open/Delete Methods

        #region Constructors/Finalizer

        internal MonitorCollectionStorage(string path, ICryptographicEngine cryptographicEngine)
        {
            Contract.Requires(!String.IsNullOrEmpty(path));
            Contract.Requires(cryptographicEngine != null);

            Folder = path;
            _cryptographicEngine = cryptographicEngine;

            var files = Directory.EnumerateFiles(path, MONITOR_FILE_SEARCH_PATTERN, SearchOption.TopDirectoryOnly);

            foreach (var file in files)
            {
                var storage = MonitorStorage.Open(Path.Combine(Path.GetDirectoryName(file), Path.GetFileNameWithoutExtension(file)), cryptographicEngine);
                var activeDays = new MonitoringActiveDays(storage.ActiveDays);
                var statistic = new MonitoringStatistic(storage.Statistic, activeDays, storage.CreateDate);

                _monitors.Add(storage.ID, new Monitor(storage, statistic, activeDays));
            }
        }

        ~MonitorCollectionStorage()
        {
            Dispose(false);
        }

        #endregion // Constructors/Finalizer

        #region IMonitorCollectionStorage Members

        public int Count
        {
            get
            {
                return _monitors.Count;
            }
        }

        public int GetActiveCount()
        {
            int count = 0;

            foreach (var monitor in _monitors.Values)
            {
                if (monitor.Active)
                {
                    count += 1;
                }
            }

            return count;
        }

        public IEnumerator<IMonitor> GetEnumerator()
        {
            return _monitors.Values.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _monitors.Values.GetEnumerator();
        }

        public int Add(MonitorType type, string title, string description, DateTime created, bool active)
        {
            int id = GenerateMonitorID();

            var storage = MonitorStorage.Create(Path.Combine(Folder, GenerateMonitorFileName(id)), true, _cryptographicEngine, id, type, title, description, created, active);
            var activeDays = new MonitoringActiveDays(storage.ActiveDays);
            var statistic = new MonitoringStatistic(storage.Statistic, activeDays, storage.CreateDate);

            _monitors.Add(id, new Monitor(storage, statistic, activeDays));

            if (MonitorAdded != null)
            {
                MonitorAdded(this, id);
            }

            return id;
        }

        public void Remove(int id)
        {
            Contract.Requires(id > 0);
            Contract.Assert(_monitors.ContainsKey(id));

            var monitor = _monitors[id];
            _monitors.Remove(id);

            if (MonitorRemoved != null)
            {
                MonitorRemoved(this, id);
            }

            monitor.Delete();
        }

        #endregion // IMonitorCollectionStorage Members

        #region Private Methods

        private string GenerateMonitorFileName(int id)
        {
            return DateTime.Now.ToString("MMddyyyyHHmmssfffffff.") + id;
        }

        private int GenerateMonitorID()
        {
            int id = 1;

            for (; id < Int32.MaxValue; ++id)
            {
                if (!_monitors.ContainsKey(id))
                {
                    break;
                }
            }

            if (id == Int32.MaxValue)
            {
                throw new ApplicationException("Looks like you have already to many monitors... try to remove one.");
            }

            return id;
        }

        #endregion // Private Methods

        #region IDisposable Members

        public void Dispose()
        {
            GC.SuppressFinalize(this);
            Dispose(true);
        }

        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    foreach (var monitor in _monitors.Values)
                    {
                        monitor.Dispose();
                    }
                }

                _disposed = true;
            }
        }

        #endregion

        #region Fields

        private bool _disposed = false;
        private ICryptographicEngine _cryptographicEngine;
        private Dictionary<int, Monitor> _monitors = new Dictionary<int, Monitor>();

        #endregion // Fields
    }
}
